package com.example.demo.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.controller.dto.HandPaperDTO;
import com.example.demo.controller.dto.PaperDTO;
import com.example.demo.entity.Paper;
import com.example.demo.entity.PaperQuestion;
import com.example.demo.entity.Question;
import com.example.demo.exception.ServiceException;
import com.example.demo.mapper.PaperMapper;
import com.example.demo.service.IPaperQuestionService;
import com.example.demo.service.IPaperService;
import com.example.demo.service.IQuestionService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

import java.util.stream.Collectors;


/**
 * @descreption:
 * @author: xhr
 * @date: 2022/9/03
 */
@RestController
@RequestMapping("/paper")
public class PaperController {
    @Resource
    PaperMapper paperMapper;
    @Resource
    private IPaperService paperService;
    @Resource
    private IQuestionService questionService;
    @Resource
    private IPaperQuestionService paperQuestionService;


    //增
    @PostMapping
    public Result<?> save(@RequestBody Paper paper) {

        paperMapper.insert(paper);
        return Result.success();
    }
    //手动组卷
    @PostMapping("/handPaper")
    public Result<?> handPaper(@RequestBody HandPaperDTO handPaperDTO) {
        //最先开始删除老的数据
        UpdateWrapper<PaperQuestion> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("paper_id",handPaperDTO.getPaperId());
        paperQuestionService.remove(updateWrapper);
        if (CollUtil.isEmpty(handPaperDTO.getHandQuestionIds())){
            throw new ServiceException("-1","题目数量不足");
        }
        List<Integer> handQuestionIds = handPaperDTO.getHandQuestionIds();
        List<PaperQuestion> list = new ArrayList<>();
        for ( Integer handQuestionId:handQuestionIds){
            PaperQuestion paperQuestion = new PaperQuestion();
            paperQuestion.setPaperId(handPaperDTO.getPaperId());
            paperQuestion.setQuestionId(handQuestionId);
            list.add(paperQuestion);
        }
        paperQuestionService.saveBatch(list);
        return Result.success();
    }
    //自动组卷
    @PostMapping("/autoPaper")
    public Result<?> autoPaper(@RequestBody PaperDTO paperDTO) {
        //先查出是响应课程的题目
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id",paperDTO.getCourseId());
        //再用依据type分类
        List<Question> questionlist = questionService.list(queryWrapper);
        List<Question> type1List = questionlist.stream().filter(question -> question.getType()==1).collect(Collectors.toList());
        List<Question> type2List = questionlist.stream().filter(question -> question.getType()==2).collect(Collectors.toList());
        List<Question> type3List = questionlist.stream().filter(question -> question.getType()==3).collect(Collectors.toList());
        if (type1List.size()<paperDTO.getType1()){
//            throw new ServiceException("-1","选择题数量不足");
            return Result.error("-1","选择题数量不足");
        }
        if (type2List.size()<paperDTO.getType2()){
//            throw new ServiceException("-1","判断题数量不足");
            return Result.error("-1","判断题数量不足");
        }
        if (type3List.size()<paperDTO.getType3()){
//            throw new ServiceException("-1","简答题数量不足");
            return Result.error("-1","简答题数量不足");
        }
        //最先开始删除老的数据
        UpdateWrapper<PaperQuestion> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("paper_id",paperDTO.getPaperId());
        paperQuestionService.remove(updateWrapper);


        //开始随机组卷
//        int size=type1List.size();
//        List<Integer> type1RandomList = getEleList(size, paperDTO.getType1());
//        List<PaperQuestion> paperQuestion1 = new ArrayList<>();
//        for ( Integer index:type1RandomList){
//            Question question = type1List.get(index);
//            PaperQuestion paperQuestion = new PaperQuestion();
//            paperQuestion.setPaperId(paperDTO.getPaperId());
//            paperQuestion.setQuestionId(question.getId());
//            paperQuestion1.add(paperQuestion);
//        }
        List<PaperQuestion> paperQuestion = getPaperQuestion(type1List.size(), paperDTO.getType1(), type1List, paperDTO.getPaperId());
        paperQuestion.addAll(getPaperQuestion(type2List.size(), paperDTO.getType2(), type2List, paperDTO.getPaperId()));
        paperQuestion.addAll(getPaperQuestion(type3List.size(), paperDTO.getType3(), type3List, paperDTO.getPaperId()));
        paperQuestionService.saveBatch(paperQuestion);
        return Result.success();
    }
    //封装随机获取试卷试题方法
    private List<PaperQuestion> getPaperQuestion(int questionSize,int paperQuestionSize,List<Question> source,Integer paperId){
        List<Integer> typeRandomList = getEleList(questionSize, paperQuestionSize);
        List<PaperQuestion> list = new ArrayList<>();
        for ( Integer index:typeRandomList){
            Question question = source.get(index);
            PaperQuestion paperQuestion = new PaperQuestion();
            paperQuestion.setPaperId(paperId);
            paperQuestion.setQuestionId(question.getId());
            list.add(paperQuestion);
        }
        return list;
    }
    //封装获取数组随机子组方法
    private  List<Integer> getEleList(int sourceSize, int resultSize){
        List<Integer> list = CollUtil.newArrayList();
        for (int i=0;i<sourceSize;i++){
            list.add(i);
        }
        return RandomUtil.randomEleList(list,resultSize);
    }
    // 改
    @PutMapping
    public Result<?> update(@RequestBody Paper paper) {
        paperMapper.updateById(paper);
        return Result.success();
    }
    // 删
    @DeleteMapping("/{id}")
    public Result<?> update(@PathVariable Long id) {
        paperMapper.deleteById(id);
        return Result.success();
    }
    //单查
    @GetMapping("/view/{paperId}")
    public Result<?> view (@PathVariable Integer paperId){
        List<Question> list =paperQuestionService.selectQuestions(paperId);
        return Result.success(list);
    }

    //全查（给其他vue用）
    @GetMapping
    public Result<?> findAll(){
        return Result.success(paperService.list());
    }

    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(defaultValue = "10") Integer pagesize,
                              @RequestParam(defaultValue = "1") Integer pagenum,
                              @RequestParam(defaultValue = "") String search,
                              @RequestParam(required = false) Integer courseId) {
        LambdaQueryWrapper<Paper> wrapper = Wrappers.<Paper>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Paper::getName, search);
        }
        if (courseId!=null) {
            wrapper.eq(Paper::getCourseId, courseId);
        }
        return Result.success(paperMapper.selectPage(new Page<>(pagenum, pagesize), wrapper));
    }
}
